<template>
  <a-spin :spinning="loading">
    <a-tree
      v-if="treeData?.length"
      :blockNode="true"
      :disabled="disabled"
      :tree-data="treeData"
      :defaultExpandAll="true"
      :autoExpandParent="true"
      :fieldNames="{ children: 'children', title: 'name', key: 'id' }"
      @select="handleSelectTree"
      v-model:selectedKeys="selectedKeys"
    >
      <template #title="{ name }">
        <div class="ellipsis-label" :title="name">
          {{ name }}
        </div>
      </template>
    </a-tree>
    <a-empty v-else :image="simpleImage" />
  </a-spin>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getUavTree } from '@/api/organization'
import type { TreeProps } from 'ant-design-vue'
import { Empty } from 'ant-design-vue'
const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE

const emit = defineEmits(['selectNode', 'updateCurrent'])

defineProps({
  searchPlaceholder: {
    type: String,
    default: '请输入'
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const loading = ref(false)

const treeData = ref<TreeProps['treeData']>([]) // 树数据
const selectedKeys = ref<string[] | number[]>([]) // 选中的key

// 树节点选中
function handleSelectTree(
  _selectedKeys: any,
  e: { selected: boolean; selectedNodes: any }
) {
  // console.log('======选中树节点======', e.selectedNodes[0])
  emit('selectNode', e.selectedNodes[0])
}

function initTreeFun() {
  loading.value = true
  getUavTree()
    .then((res) => {
      console.log(res, '无人机树')
      treeData.value = res
      emit('updateCurrent', res[0])
      loading.value = false
    })
    .catch(() => {
      treeData.value = []
      loading.value = false
    })
}

onMounted(() => {
  initTreeFun()
})

defineExpose({ initTreeFun })
</script>

<style lang="less" scoped>
.ant-spin-spinning {
  display: flex;
  justify-content: center;
  align-items: center;
}

.ant-spin-nested-loading,
.ant-spin-spinning {
  height: 100%;
}

.ellipsis-label {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-break: break-all;
}
</style>
